<script setup>
  // 导入网络请求api
  import { uniFetch } from '@/apis/uni-fetch.js'
  import { ref, reactive } from 'vue'
  import { useUserStore } from '@/stores/users.js'
  // 表单元素的 ref 属性
  const accountForm = ref()

  // 表单数据
  const formData = reactive({
    account: 'zyb123',
    password: '123456',
  })

  // 定义表单数据验证规则
  const accountRules = reactive({
    account: {
      rules: [
        { required: true, errorMessage: '请输入登录账号' },
        { pattern: '^[a-zA-Z0-9]{6,8}$', errorMessage: '登录账号格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入登录密码' },
        { pattern: '^\\d{6}$', errorMessage: '登录密码格式不正确' },
      ],
    },
  })

  async function onFormSubmit() {
    // 提交表单数据
    try {
      // 验证通过
      const formData = await accountForm.value.validate()

      // 请求服务器登录接口获取服务器响应结果
      let res = await uniFetch.post('/driver/login/account', formData)
      // console.log(res.data.data)
      const token = res.data.data

      // 将res.data.data中的token存储起来
      const store = useUserStore()
      store.token = token //向仓库保存一个token并且持久化

      // 跳转到任务列表
      // redirectTo只能跳转到普通的页面，不能跳转到tabbar配置的页面,所以只能通过switchTab方式来跳转
      uni.switchTab({
        url: '/pages/task/index',
      })
    } catch (err) {
      // 验证失败
      console.log('验证失败：', err)
    }
  }
</script>

<template>
  <uni-forms
    class="login-form"
    ref="accountForm"
    :model="formData"
    :rules="accountRules"
  >
    <uni-forms-item name="account">
      <input
        type="text"
        placeholder="请输入账号"
        v-model="formData.account"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <input
        type="text"
        placeholder="请输入密码"
        class="uni-input-input"
        v-model="formData.password"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <button class="submit-button" @click="onFormSubmit">登录</button>
  </uni-forms>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
